#include<iostream>
#include<pthread.h> 
#include<unistd.h>

#define THREAD_MAX_NUM 5

int tickets = 10000;

class ThreadData
{
  public:
    ThreadData(int uid,pthread_mutex_t* mtx):_uid(uid),_mtx(mtx){}
  public:
    int _uid;
    pthread_mutex_t* _mtx;
};

void* ThreadRun(void* args)
{
  ThreadData* data = (ThreadData*)args;

  //抢票逻辑
  while(1)
  {
    //抢票这段资源为临界资源，我们为其加锁
    pthread_mutex_lock(data->_mtx);
    if(tickets > 0)
    {
      usleep(1000);//延迟1000微秒
      tickets--; 
      printf("thread %d 抢了一张票。还剩 %d 张票\n",data->_uid,tickets);
      pthread_mutex_unlock(data->_mtx); //解锁 
    }else 
    {
      //这里也必须解锁。如果上面条件不成立，那么就要在这里进行解锁。
      pthread_mutex_unlock(data->_mtx); //解锁 
      break; 
    }
  }
  return nullptr;
}

int main()
{
  //创建局部锁 
  pthread_mutex_t mtx; 
  //初始化局部锁 
  pthread_mutex_init(&mtx,nullptr);
  pthread_t tids[THREAD_MAX_NUM];
  for(int i = 0 ; i < THREAD_MAX_NUM ; i++)
  {
    ThreadData* data = new ThreadData(i+1,&mtx);
    pthread_create(tids+i , nullptr,ThreadRun,(void*)data);
  }
  
  for(int i = 0 ;  i < THREAD_MAX_NUM ; i++)
  {
    pthread_join(tids[i],nullptr);
  }
  //销毁锁
  pthread_mutex_destroy(&mtx);
  return 0;
}
